package com.library.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.library.entity.BorrowRecord;
import com.library.util.DBConnection;

/**
 * 借阅记录数据访问对象
 */
public class BorrowRecordDAO {
    
    /**
     * 添加借阅记录
     */
    public boolean addBorrowRecord(BorrowRecord record) {
        String sql = "INSERT INTO borrow_records (user_id, book_id, borrow_date, return_date, status) "
                + "VALUES (?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, record.getUserId());
            pstmt.setInt(2, record.getBookId());
            pstmt.setTimestamp(3, new Timestamp(record.getBorrowDate().getTime()));
            pstmt.setTimestamp(4, new Timestamp(record.getReturnDate().getTime()));
            pstmt.setInt(5, record.getStatus());
            
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBConnection.close(conn, pstmt, null);
        }
    }
    
    /**
     * 更新借阅记录（归还图书）
     */
    public boolean returnBook(int recordId) {
        String sql = "UPDATE borrow_records SET actual_return_date = ?, status = ? WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, new Timestamp(new Date().getTime()));
            pstmt.setInt(2, 1); // 1表示已归还
            pstmt.setInt(3, recordId);
            
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBConnection.close(conn, pstmt, null);
        }
    }
    
    /**
     * 根据ID查询借阅记录
     */
    public BorrowRecord getRecordById(int id) {
        String sql = "SELECT * FROM borrow_records WHERE id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        BorrowRecord record = null;
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                record = new BorrowRecord();
                record.setId(rs.getInt("id"));
                record.setUserId(rs.getInt("user_id"));
                record.setBookId(rs.getInt("book_id"));
                record.setBorrowDate(rs.getTimestamp("borrow_date"));
                record.setReturnDate(rs.getTimestamp("return_date"));
                record.setActualReturnDate(rs.getTimestamp("actual_return_date"));
                record.setStatus(rs.getInt("status"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBConnection.close(conn, pstmt, rs);
        }
        
        return record;
    }
    
    /**
     * 查询用户的所有借阅记录
     */
    public List<BorrowRecord> getRecordsByUserId(int userId) {
        String sql = "SELECT * FROM borrow_records WHERE user_id = ? ORDER BY borrow_date DESC";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<BorrowRecord> records = new ArrayList<>();
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getInt("id"));
                record.setUserId(rs.getInt("user_id"));
                record.setBookId(rs.getInt("book_id"));
                record.setBorrowDate(rs.getTimestamp("borrow_date"));
                record.setReturnDate(rs.getTimestamp("return_date"));
                record.setActualReturnDate(rs.getTimestamp("actual_return_date"));
                record.setStatus(rs.getInt("status"));
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBConnection.close(conn, pstmt, rs);
        }
        
        return records;
    }
    
    /**
     * 查询用户的当前借阅记录（未归还）
     */
    public List<BorrowRecord> getCurrentRecordsByUserId(int userId) {
        String sql = "SELECT * FROM borrow_records WHERE user_id = ? AND status = 0 ORDER BY borrow_date DESC";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<BorrowRecord> records = new ArrayList<>();
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getInt("id"));
                record.setUserId(rs.getInt("user_id"));
                record.setBookId(rs.getInt("book_id"));
                record.setBorrowDate(rs.getTimestamp("borrow_date"));
                record.setReturnDate(rs.getTimestamp("return_date"));
                record.setActualReturnDate(rs.getTimestamp("actual_return_date"));
                record.setStatus(rs.getInt("status"));
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBConnection.close(conn, pstmt, rs);
        }
        
        return records;
    }
    
    /**
     * 查询所有借阅记录
     */
    public List<BorrowRecord> getAllRecords() {
        String sql = "SELECT * FROM borrow_records ORDER BY borrow_date DESC";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<BorrowRecord> records = new ArrayList<>();
        
        try {
            conn = DBConnection.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            
            while (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getInt("id"));
                record.setUserId(rs.getInt("user_id"));
                record.setBookId(rs.getInt("book_id"));
                record.setBorrowDate(rs.getTimestamp("borrow_date"));
                record.setReturnDate(rs.getTimestamp("return_date"));
                record.setActualReturnDate(rs.getTimestamp("actual_return_date"));
                record.setStatus(rs.getInt("status"));
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBConnection.close(conn, stmt, rs);
        }
        
        return records;
    }
    
    /**
     * 查询逾期未还的借阅记录
     */
    public List<BorrowRecord> getOverdueRecords() {
        String sql = "SELECT * FROM borrow_records WHERE status = 0 AND return_date < ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<BorrowRecord> records = new ArrayList<>();
        
        try {
            conn = DBConnection.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, new Timestamp(new Date().getTime()));
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getInt("id"));
                record.setUserId(rs.getInt("user_id"));
                record.setBookId(rs.getInt("book_id"));
                record.setBorrowDate(rs.getTimestamp("borrow_date"));
                record.setReturnDate(rs.getTimestamp("return_date"));
                record.setActualReturnDate(rs.getTimestamp("actual_return_date"));
                record.setStatus(rs.getInt("status"));
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBConnection.close(conn, pstmt, rs);
        }
        
        return records;
    }
}
